@page "/HomePage"
@using System.Security.Claims
@using BootstrapBlazorApp.Server.Components.CustomComponent;
<Layout ShowGotoTop="true"  SideWidth="300"
        ShowCollapseBar="false" IsPage="true">
    <Header>
        <HeaderComponent User="@user" OnQuestionsFiltered="HandleQuestionsFiltered" Type="false" Questions="questions"></HeaderComponent>
    </Header>

    <Side>
        <div style="margin: 3%;margin-top: 5%">
            <Card IsShadow="true" Color="Color.Secondary">
                <BodyTemplate>
                    <QuestionCalendar AnsDetails="@_answerDetails" NowMonth="@DateTime.Today.Month"></QuestionCalendar>
                </BodyTemplate>
            </Card>
        </div>
        <div style="margin: 0 3%">
            <Card IsShadow="true" Color="Color.Secondary">
                <BodyTemplate>
                    <div style="color: black;">
                        <div style="display: flex">
                            <h6 style="font-weight: bold">热门题库</h6>
                            <i class="bi bi-fire" style="color: #f86323;margin-left: 3px"></i>
                        </div>
                        <div @onclick="() => selectCategory(4)">
                            <QuestionCard Img_url="https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/dynamic-programming/cover"
                                          Title="并发编程100题"
                                          Introduction="选取面试最常见的并发编程题目"></QuestionCard>
                        </div>
                        <div>
                            <QuestionCard Img_url="https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/top-interview-150/cover"
                                          Title="集合基础"
                                          Introduction="更详细的知识点拆分，让入门更简单"></QuestionCard>
                        </div>
                        <div>
                            <QuestionCard Img_url="https://assets.leetcode.cn/aliyun-lc-upload/study_plan_v2/sql-premium-50/cover"
                                          Title="SQL经典题型"
                                          Introduction="更详细的知识点拆分，让入门更简单"></QuestionCard> 
                        </div>
                        
                    </div>
                </BodyTemplate>
            </Card>
        </div>
    </Side>
    
    <Main>
        <div style="align-items: center;margin: 0 auto;">
            @*分类*@
            <Card Color="Color.Secondary">
                <BodyTemplate>
                    <div style="margin: -1% 0;font-size: 1rem;">
                        <Nav IsPills="true" IsFill="true" IsJustified="true">
                            @foreach( var (index,category) in categorys.Select((value, index) => (index, value)))
                            {
                            <a class="nav-link nav-item @(index==activeIndex?"active":" ")" @onclick="()=>selectCategory(index)">@category</a>
                            }
                        </Nav>
                    </div>
                </BodyTemplate>
            </Card>
            <div style="margin-bottom: 3%"></div>
            <Table TItem="QuestionWithStatus" 
                   IsStriped="true" 
                   AllowResizing="true" 
                   IsPagination="true"
                   ShowLoading="true"
                   PageItemsSource="@PageItemsSource" 
                   OnQueryAsync="OnQueryAsync"
                   IsAutoRefresh="@IsAutoRefresh" 
                   AutoRefreshInterval="1000">
                <TableColumns>
                    @*完成状态*@
                    <TableColumn @bind-Field="@context.Status" Width="100" Align="Alignment.Center" Filterable="true">
                        <FilterTemplate>
                            <MultiFilter ShowSearch="false" Items="questionsWithStatus.Select(i => new SelectedItem(i.Status.ToString()!, i.Status.ToString()!)).DistinctBy(i => i.Value)"></MultiFilter>
                        </FilterTemplate>
                        <Template Context="value">
                            @if (value.Value)
                            {
                                <i class="bi bi-check-circle" style="color: #28a745;"></i>
                            }
                            else
                            {
                                <i class="bi bi-dash"></i>
                            }
                        </Template>
                    </TableColumn>

                    @*题目名*@
                    <TableColumn @bind-Field="@context.Title" Width="500" Align="Alignment.Center">
                        <Template Context="value">
                            <a href="/qdetail/@value.Row.QId">@value.Value</a>
                        </Template>
                    </TableColumn>

                    @*题目标签*@
                    <TableColumn @bind-Field="@context.Tag" Align="Alignment.Center" Filterable="true">
                        <Template Context="value">
                            @*假设全部tag作为一个字符串存储，用、分隔*@
                            @foreach (var tag in value.Value.Split('、'))
                            {
                                <div class="col-4 col-sm-auto" style="margin-right: 5px">
                                    <Tag Color="Color.Warning">@tag</Tag>
                                </div>
                            }
                        </Template>
                    </TableColumn>

                    @*难度*@
                    <TableColumn @bind-Field="@context.Difficulty" Width="100" Align="Alignment.Center" Filterable="true">
                        <FilterTemplate>
                            <MultiFilter ShowSearch="false" Items="questionsWithStatus.Select(i => new SelectedItem(i.Difficulty.ToString()!, i.Difficulty.ToString()!)).DistinctBy(i => i.Value)"></MultiFilter>
                        </FilterTemplate>
                        <Template Context="value">
                            <div class="@setDifficultyColor(@value.Value)">@value.Value</div>
                        </Template>
                    </TableColumn>
                </TableColumns>
            </Table>
        </div>
        
    </Main>
    
</Layout>

@inject NavigationManager NavigationManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject SwalService SwalService
@code {
    //用户
    private ClaimsPrincipal? _user;
    private User user;
    
    //问题信息
    private List<Question> questions=new List<Question>();
    private List<bool> status=new List<bool>();
    //问题列表（带有完成状态）
    private List<QuestionWithStatus> questionsWithStatus=new List<QuestionWithStatus>();
    
    //分类导航栏
    private List<string> categorys = new List<string>() {
        "全部","集合","框架","数据库","并发编程","设计模式","计算机基础","其他"
    };
    private int activeIndex = 0;
    
    //分页
    private static IEnumerable<int> PageItemsSource => new int[]
    {
        15,
        20,
        50
    };
    
    //答题信息（用于日历）
    private List<AnswerDetail> _answerDetails;
    private bool IsAutoRefresh = false;
    
    
    protected override async Task OnInitializedAsync()
    {
        base.OnInitializedAsync();
        //获取当前用户对象
        _user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
        
        if (_user == null)
        {
            return;
        }

        var value = _user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (value != null)
        {
            var user_id = int.Parse(value);
            user = User.Find(user_id);
        }
        
        //获取题目列表
        GetAllQuestions();
        //获取答题列表
        _answerDetails=getAnswerDetail();
    }

    //搜索问题
    private async Task HandleQuestionsFiltered(List<QuestionWithStatus> qs)
    {
        questionsWithStatus = qs;
        //触发表格刷新
        IsAutoRefresh = true;
        StateHasChanged();
        //等待后关闭自动刷新
        await Task.Delay(2000);
        IsAutoRefresh= false;
    }
    
    //加载列表
    private Task<QueryData<QuestionWithStatus>> OnQueryAsync(QueryPageOptions options)
    {
        
        // 通过 options 获得用户组合的过滤条件
        var filters = options.ToFilter();

        // 使用内置扩展方法 ToFilter 获得过滤条件
        var items = questionsWithStatus.Where(filters.GetFilterFunc<QuestionWithStatus>());
        //获得总数
        var enumerable = items.ToList();
        var total = enumerable.Count;
        // 内存分页
        items = enumerable.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();
    
        return Task.FromResult(new QueryData<QuestionWithStatus>()
        {
            Items = items,
            TotalCount = total,
            IsFiltered = filters.HasFilters()
        });
        
        
    }
    
    public void GetAllQuestions()
    {
        questions = Question.Where(q => true).ToList();
        //获取完成状态
        getALLStatus();
    }

    private void getALLStatus()
    {
        foreach (var q in questions)
        {
            bool st = false;
            var record=AnswerDetail.Where(a => a.QuestionId == q.Id && a.UserId == user.Id).First();
            if (record != null)
            {
                st = true;
            }
            questionsWithStatus.Add(new QuestionWithStatus(){
                QId=q.Id,
                Title=q.Title,
                Tag=q.Tag,
                Difficulty=q.Difficulty,
                Category=q.Category,
                Status=st
            });
        }
    }

    public List<AnswerDetail> getAnswerDetail()
    {
       return AnswerDetail.Where(a => a.UserId == user.Id).ToList(); 
    }

    private string setDifficultyColor(string dif)
    {
        return dif switch
        {
            "简单" => "easy-color",
            "中等" => "medium-color",
            "困难" => "hard-color",
            _ => ""
        };
    }
    
    //点击导航栏分类
    private async void selectCategory(int index)
    {
        //触发表格刷新
        IsAutoRefresh = true;
        //清空qs列表
        questionsWithStatus.Clear();
        getALLStatus();
        if (index < 0 || index >= categorys.Count)
        {
            return;
        }
        if (categorys[index] != "全部")
        {
            questionsWithStatus = questionsWithStatus.Where(q => q.Category == categorys[index]).ToList();
        }
        //更改激活的分类框
        activeIndex = index;
        StateHasChanged();
        
        //等待后关闭自动刷新
        await Task.Delay(1500);
        IsAutoRefresh= false;
    }
    

}
